package com.yy.studyspringboot.concurrent;

import java.util.concurrent.*;

public class ExchangerTest {
    /**  Exchanger---同步交换器
        下面案例：A B 两个线程一人执行一次，交换执行
     */

    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> ex = new Exchanger<>();
        new A(ex).start();
        new B(ex).start();
    }


}

class A extends Thread{
    private Exchanger<String> ex;
    public A(Exchanger<String> ex){
        this.ex = ex;
    }
    @Override
    public void run() {
        String str = null;

        try {
            str = ex.exchange("Hello?");
            System.out.println(str);

            str = ex.exchange("A?");
            System.out.println(str);

            str = ex.exchange("B?");
            System.out.println(str);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
class B extends Thread{
    private Exchanger<String> ex;
    public B(Exchanger<String> ex){
        this.ex = ex;
    }
    @Override
    public void run() {
        String str = null;

        try {
            str = ex.exchange("Hi?");
            System.out.println(str);

            str = ex.exchange("a");
            System.out.println(str);

            str = ex.exchange("2");
            System.out.println(str);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}